package com.relife.sys.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.model.AjaxJson;
import com.relife.common.model.Page;
import com.relife.common.utils.StringUtil;
import com.relife.core.easyui.Easyui;
import com.relife.core.entity.AreaEntity;
import com.relife.core.qbc.QbcQuery;
import com.relife.sys.service.AreaService;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * 地域管理
 * @author ANT
 * @date 2016-07-01 10:47:51
 */
@Controller
@RequestMapping("sys/area")
public class AreaController extends BaseController {
	@Autowired
	private AreaService areaService;

	 
	@RequestMapping
	public String areaList(HttpServletRequest req) {
		return "sys/area/areaList";
	}

	/**
	 * 数据列表
	 * 
	 * @author ANT
	 * @date 2016-07-01 10:47:51
	 * @param page
	 */
	@RequestMapping
	public void listData(Integer id, Page page, HttpServletResponse res) {
		QbcQuery qbc = new QbcQuery(AreaEntity.class);
		if (StringUtil.isEmpty(id)) {
			qbc.add(Restrictions.eq("parent.id",0));
			qbc.addOrder(Order.asc("idCode"));;
		} else {
			qbc.add(Restrictions.eq("parent.id", id));
		}
		areaService.getPage(qbc, page);
		Easyui.treegrid(page, res);
	}

	/**
	 * @author ANT
	 * @date 2016-07-01 10:47:51
	 * @param area
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String area(AreaEntity area, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(area.getId())) {
			area = areaService.get(AreaEntity.class, area.getId());
		}
		req.setAttribute("page", area);
		return "sys/area/area";
	}
 
 
    /**
	 * 保存
	 * @author ANT
	 * @date 2016-07-01 10:47:51
	 * @param area
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson save(AreaEntity area, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			areaService.saveOrUpdate(area);
		} catch (Exception e) {
		    j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

     /**
	 * 删除
     * @author ANT
	 * @date 2016-07-01 10:47:51
	 * @param area
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson del(AreaEntity area) {
		AjaxJson j = new AjaxJson();
		try {
			areaService.delete(area);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}
}
